package it.polimi.digitalstate.manager;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import it.polimi.digitalstate.dto.CitizenDTO;
import it.polimi.digitalstate.dto.*;
import it.polimi.digitalstate.entities.IEntity;


public  class DTOEntityTransformer {
	
	
	public static IEntity getEntity(EntityManager em,IDataTransferObject dto){
		String objectType="";
		if(dto instanceof CitizenDTO){
			objectType="citizen";
		}
		if(dto instanceof ElectionDTO){
			objectType="election";
		}
		if(dto instanceof JoinrequestDTO){
			objectType="joinrequest";
		}
		if(dto instanceof MembershipDTO){
			objectType="membership";
		}
		if(dto instanceof PartyDTO){
			objectType="party";
		}
		if(dto instanceof UserDTO){
			objectType="user";
		}
		if(dto instanceof JoinVoteDTO){
			objectType="joinVote";
		}
			
		if(objectType==""){
			//TODO throw an exception
			System.out.println("Tipo non trovato");
		}
		
		Query q = em.createNamedQuery(objectType + "_getByID");
		System.out.println("Transformer ID: " + dto.getID());
		q.setParameter("id", dto.getID());
		Object[] res = q.getResultList().toArray();
		if(res.length==1){
			return (IEntity)res[0];
		}
		//TODO better... throw an exception  :D
		System.out.println("Res!=1");
		return null;
		
	}
}
